package com.ddd.mill.infrastructure.persistent.handler;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.baomidou.mybatisplus.core.metadata.TableInfo;
import com.baomidou.mybatisplus.core.metadata.TableInfoHelper;
import com.baomidou.mybatisplus.core.toolkit.Constants;
import com.ddd.mill.infrastructure.utils.SnowFlake;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.Objects;

@Slf4j
@Component
public class MybatisMetaObjectHandler implements MetaObjectHandler {
    @Autowired
    private SnowFlake snowFlake;

    @Override
    public void insertFill(MetaObject metaObject) {
        // 设置主键值
        TableInfo tableInfo = metaObject.hasGetter(Constants.MP_OPTLOCK_ET_ORIGINAL) ?
                TableInfoHelper.getTableInfo(metaObject.getValue(Constants.MP_OPTLOCK_ET_ORIGINAL).getClass())
                : TableInfoHelper.getTableInfo(metaObject.getOriginalObject().getClass());
        if (Objects.nonNull(tableInfo) && this.getFieldValByName(tableInfo.getKeyProperty(), metaObject) == null) {
            this.setFieldValByName(tableInfo.getKeyProperty(), snowFlake.nextId(), metaObject);
        }
        this.strictUpdateFill(metaObject, "createTime", LocalDateTime.class, null);
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        this.strictUpdateFill(metaObject, "updateTime", LocalDateTime.class, null);
    }
}
